package com.changgou.order.consumer;

import com.alibaba.fastjson.JSON;
import com.changgou.order.pojo.OrderLog;
import com.changgou.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ：hushengjin
 */

@Component
@RabbitListener(queues = "${mq.pay.queue.order}")
public class OrderPayMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    /**
     * 监听消息
     *
     * @param msg
     */
    @RabbitHandler
    public void consumeMessage(String msg) {
        //将msg转换成Map对象
        Map<String, String> resultMap = JSON.parseObject(msg, Map.class);
        //返回状态码
        String return_code = resultMap.get("return_code");
        String result_code = resultMap.get("result_code");
        if (return_code.equalsIgnoreCase("SUCCESS")) {
            //获取out_trade_no
            String out_trade_no = resultMap.get("out_trade_no");
            //获取订单日志
            OrderLog orderLog = (OrderLog) redisTemplate.boundHashOps("OrderLog").get(out_trade_no);
            //支付成功
            if (result_code.equalsIgnoreCase("SUCCESS")) {
                if (orderLog != null) {
                    //修改订单状态
                    orderService.updateStatus(orderLog.getOrderId(), resultMap.get("transaction_id"), orderLog);
                }
            } else {
                //删除订单,支付失败
                orderService.deleteOrder(orderLog);
            }
        }
    }

}
